<template>
  <div>
    <el-breadcrumb separator="/" class="submenu">
      <el-breadcrumb-item :to="{ path: '/Index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">数据权限分配</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="main-table">
      <template>
        <el-form :model="selectionForm">
          <el-tabs v-model="activeName2" type="card" @tab-click="handleClick">
            <el-tab-pane label="采购组织" name="purOrg">
              <!-- <el-transfer style="text-align: left; display: inline-block" @change="purOrgChange()" v-model="selectionForm.purOrgSection"
                filterable :render-content="renderFunc" :titles="['可选采购组织', '已选采购组织']" :button-texts="['到左边', '到右边']" :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
                }" :data="purOrgData">
              </el-transfer> -->
              <vendors-transfer ref="trans" 
                width="100%" :checkName="['id','purOrgName']" 
                 @transAdd="addTrans" :title="{left:'可选采购组织',right:'已选采购组织'}"
                :searchForm="searchPurOrgForm" :selectData="selectionForm.purOrgSection" :isQsparams = false
                :url="lib.config.host.masterData + '/system/purOrgMgt/purOrg/query'">
                </vendors-transfer>
            </el-tab-pane>


            <el-tab-pane label="采购组" name="purGroup">
              <!-- <el-transfer style="text-align: left; display: inline-block" v-model="selectionForm.purGroupSection" filterable :render-content="renderFunc"
               :titles="['可选采购组', '已选采购组']" :button-texts="['到左边', '到右边']" :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
                }" :data="purGroupData">
              </el-transfer> -->

              <vendors-transfer ref="transs" 
                width="100%" :checkName="['id','purGroupName']" 
                :title="{left:'可选采购组',right:'已选采购组'}"
                :searchForm="searchPurGroupForm" :selectData="selectionForm.purGroupSection" :isQsparams = true
                :url="lib.config.host.system + '/mdata/purOrgMgt/purGroup/getPostByPurOrgIdList'">
                </vendors-transfer>
            </el-tab-pane>

             <el-tab-pane label="物料品类" name="material">     
               <el-tree :data="treeData" :props="treeProps" node-key="id" show-checkbox ref="elTree" :default-checked-keys="defaultTreeData"></el-tree>
             </el-tab-pane>
          </el-tabs>
        </el-form>
        <div slot="footer" class="panel_end_small clearfix">
          <el-button class="fr"  type="primary" @click="allowData()">确 定</el-button>
        </div>
      </template>
    </div>

  </div>
</template>
<script>
  import axios from 'axios'
  import qs from 'qs';
  import vendorsTransfer from '@/components/common/select-ext/vendorsTransfer.vue';
  export default {
  components: {
      vendorsTransfer
    },
    data() {
      return {
        activeName2: 'purOrg',
        selectId : '',
        selectCode : '',
        selectName : '',
       searchPurOrgForm:[
				  {key:'purOrgType', value:'1'},
				  {key:'purOrgName',type:'text',placeholder:'请输入名称',value:''}
        ],
        searchPurGroupForm:[
          // {key:'purGroupName',type:'text',placeholder:'请输入名称',value:''},
           {key:'purOrgIds',type : '',placeholder:'',value:''}
     
        ],
        purOrgData: [],    
        purGroupData: [],    
        sourceLgData: [],
        selectionForm: {
          purOrgSection: [],
          purGroupSection: [],
          sourceLgSection: []    
        },
        afterForm: {
          purOrgIds: '',
          factoryIds: '',
           pageNo :1,
           pageSize: 100

        },
        tranForm: {
          purOrgJsonStr: '',
          purGroupJsonStr: '',
          matCategoryJsonStr: ''
        },
        purOrgIdStr : '',
        treeProps: {
          label: 'categoryName',
          children: 'children',
          isLeaf: 'isLeaf' //判断是否含有子节点的判断
        },
        currentValue:'',
        resultData:{},
        defaultTreeData:[],
        treeData:[]
      };
    },
    created() {
      //初始获取已选中的品类
      this.axios.get(this.lib.config.host.system + '/system/dauscgt/findByUserId/' + this.$route.query.userId).then((res)=>{
        res.data.forEach((item)=>{
          this.defaultTreeData.push(item.categoryId);
        });
        this.axios.post(this.lib.config.host.system + '/mainsupplycategory/query', {}).then((res)=>{
          this.treeData = this.transformToTreeFormat(res.data);
        });
      });
    },
    mounted() {
      this.searchTrans();
      this.searchGroupTrans();
    },
    methods: {
        handleClick(tab, event) {
        switch (this.activeName2){     
          case 'purOrg':
            break;
           case 'purGroup':
            break;  
          default:
            break;
        }
      },
      getpurOrgIdStr(){
        if (this.selectionForm.purOrgSection.length > 0) {
          for (var i = 0; i < this.selectionForm.purOrgSection.length; i++) {
            this.purOrgIdStr += this.selectionForm.purOrgSection[i].id + ","
          }
          this.purOrgIdStr = this.purOrgIdStr.substr(0, this.purOrgIdStr.length - 1);
          console.log(this.purOrgIdStr);
          this.searchPurGroupForm[0].value = this.purOrgIdStr;
        }
      },
      searchTrans(parameter){
        //穿梭框右边数据获取
        this.axios.get(this.lib.config.host.masterData + "/system/purOrgMgt/purOrg/getPurOrgByUserId/"+this.$route.query.userId).then((res) => {
          this.selectionForm.purOrgSection=res.data;
           //采购组织
           console.log(this.selectionForm.purOrgSection);
          this.getpurOrgIdStr();
          this.$nextTick(()=>{
            this.$refs.trans.resetCheck();
          })
        })
        .catch(function (error) {
            console.log(error);
        });
      },
       searchGroupTrans(parameter){
        //穿梭框右边数据获取
        this.axios.get(this.lib.config.host.system + "/mdata/purOrgMgt/purGroup/getByUserId/"+this.$route.query.userId).then((res) => {
          debugger
          this.selectionForm.purGroupSection=res.data;
          this.$nextTick(()=>{
            this.$refs.transs.initData();
          })
        })
        .catch(function (error) {
            console.log(error);
        });
      },
      addTrans(data){
        if(this.activeName2==='purOrg'){
          this.getpurOrgIdStr();
          this.$nextTick(()=>{
            this.$refs.transs.initData();
          })
          let ids=[]
          data.forEach(val=>{
            ids.push(val.id)
          })
          this.selectionForm.purGroupSection.forEach((val,index)=>{
            if(!ids.some(value=>{return value===val.purOrgId})){
              this.selectionForm.purGroupSection.splice(index,1);
            }
          })
        }
      },
      renderFunc(h, option) {
        return <span > {option.label} </span>;
      },
      purOrgChange() {
        //采购组织发生变化
        //清空工厂
        // this.factoryData = [];
        // this.selectionForm.factorySection = [];
        //清空采购组
        this.purGroupData = [];
        this.selectionForm.factorySection = [];
        //重新赋值工厂
        if (this.selectionForm.purOrgSection.length>0) {
          for (var i = 0; i < this.selectionForm.purOrgSection.length; i++) {
            this.afterForm.purOrgIds += this.selectionForm.purOrgSection[i] + ","
          }
          this.afterForm.purOrgIds = this.afterForm.purOrgIds.substr(0, this.afterForm.purOrgIds.length - 1);
          //重新赋值工厂
          // this.sourceMethod("system/factoryMgt/factorys/getByPurOrgIdList", qs.stringify(this.afterForm), this.factoryData,"3");
          //重新赋值采购组
          //  this.afterForm.pageNo = 1;
          // this.afterForm.pageSize = 15;
          this.sourceMethod(this.lib.config.host.system+"/mdata/purOrgMgt/purGroup/getByPurOrgIdList", qs.stringify(this.afterForm), this.purGroupData,"4");
          this.afterForm.purOrgIds = '';
        }
      },

      allowData() {

        //采购组织
        if (this.selectionForm.purOrgSection.length > 0) {
          for (var i = 0; i < this.selectionForm.purOrgSection.length; i++) {
            this.tranForm.purOrgJsonStr += this.selectionForm.purOrgSection[i].id + ","
          }
          this.tranForm.purOrgJsonStr = this.tranForm.purOrgJsonStr.substr(0, this.tranForm.purOrgJsonStr.length - 1);
        }

        //采购组
        if (this.selectionForm.purGroupSection.length > 0) {
          for (var i = 0; i < this.selectionForm.purGroupSection.length; i++) {
            this.tranForm.purGroupJsonStr += this.selectionForm.purGroupSection[i].id + ","
          }
          this.tranForm.purGroupJsonStr = this.tranForm.purGroupJsonStr.substr(0, this.tranForm.purGroupJsonStr.length -
            1);
        }
        //物料品类
        let arr = this.$refs.elTree.getCheckedKeys();


          //采购组
        
          for (var i = 0; i < arr.length; i++) {
            this.tranForm.matCategoryJsonStr += arr[i] + ","
          }
          this.tranForm.matCategoryJsonStr = this.tranForm.matCategoryJsonStr.substr(0, this.tranForm.matCategoryJsonStr.length -
            1);
        
        //this.tranForm.matCategoryJsonStr = JSON.stringify(arr);

        this.axios.post(this.lib.config.host.system+"/system/usermgt/users/saveUserDataOpe/"+this.$route.query.userId,qs.stringify(this.tranForm)).then((response) => {
            if (response.data.length > 0) {
              for (var i = 0; i < response.data.length; i++) {
                targetData.push(response.data[i].selectId);
              }
            }
              this.$message({
              type: 'success',
              message: '保存成功!'
            });
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      transformToTreeFormat(array){
        let i,l,
          key = 'id',
          parentKey = 'parentId',
          childKey = 'children';

        if (array instanceof Array) {
          let r = [];
          let tmpMap = {};
          for (i=0, l=array.length; i<l; i++) {
            if (array[i]) {
              tmpMap[array[i][key]] = array[i];
            }
          }
          for (i=0, l=array.length; i<l; i++) {
            if (array[i] && tmpMap[array[i][parentKey]] && array[i][key] !== array[i][parentKey]) {
              if (!tmpMap[array[i][parentKey]][childKey])
                tmpMap[array[i][parentKey]][childKey] = [];
              tmpMap[array[i][parentKey]][childKey].push(array[i]);
            } else {
              r.push(array[i]);
            }
          }
          return r;
        } else {
          return [array];
        }
      }
    },
    watch:{
      value(val){
        this.currentValue = val;
      },
      resultData(val){
        this.currentValue = '';
        if (this.multiple) {
          let arr = Object.values(val);
          arr.forEach((item, index)=>{
            this.currentValue += (index === 0? '': ',') + item.categoryName;
          });
        } else {
          this.currentValue = this.resultData.categoryName;
        }
        this.$emit('input', this.currentValue);
      }
    }
  }
</script>
<style>


</style>
